package com.diandi.signature.timer;

import com.diandi.signature.batchrun.SignatureBatchRunService;
import com.diandi.signature.bean.contract.SignatureContract;
import com.diandi.signature.bean.pkgmsg.SignatureBusinessPkgmsg;
import com.diandi.signature.bean.runbatch.SignatureBatchRunInfo;
import com.diandi.signature.enums.platfrom.BatchRunStatus;
import com.diandi.signature.enums.platfrom.InterfactType;
import com.diandi.signature.manager.contract.SignatureContractManager;
import com.diandi.signature.signaturepkg.SignaturePkgMsgService;
import com.diandi.signature.url.CreateTradeNo;
import com.diandi.signature.url.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by mxp on 2017/9/19.
 */
@Component
@EnableScheduling
public class CallBackTimerTask {
    private Logger logger = LoggerFactory.getLogger(CallBackTimerTask.class);

    @Autowired
    private SignatureBatchRunService signatureBatchRunService;

    @Autowired
    private SignatureContractManager signatureContractManager;

    @Autowired
    private SignaturePkgMsgService signaturePkgMsgService;

    @Scheduled(cron = "${cron.expression.callBack}")
    public void task(){
        logger.debug("回调定时任务开始");

        String tradeNo = CreateTradeNo.createTradeNo("CBT");

        Long sp1 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] callBackTimer Start--");

        List<SignatureBatchRunInfo> toDoList = signatureBatchRunService.queryTask(Integer.valueOf(BatchRunStatus.异步通知初始化.getStatus()));
        if (toDoList == null || toDoList.isEmpty()){
            logger.debug("无需要回调的数据");
            return;
        }


        Long sp2 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] step1 use times:"+(sp2-sp1)+"--");

        SignatureContract contract = null;
        for (SignatureBatchRunInfo info : toDoList) {
            //更改状态
            logger.debug("更改数据状态");
            info.setStatus(BatchRunStatus.异步通知已抽取.getStatus());
            signatureBatchRunService.updateBatchRunInfo(info);
            logger.debug("更改数据状态完成");

            SignatureBusinessPkgmsg pkgMsg = signaturePkgMsgService.getSignaturePkgMsg(info.getSignatureCode());
            if (pkgMsg == null){
                logger.debug("未找到与[{}] 对应的请求参数");
                continue;
            }

            Map<String, String> param = GsonUtil.fronJson2Map(pkgMsg.getReturnMsg());

            try {
                logger.debug("开始发送回调");
                String result = signatureContractManager.callBusiness(param.get("code"), param.get("msg"), info.getContractCode(), info.getNotifyUrl(), info.getMerchantNo());
                if ("SUCCESS".equals(result.toUpperCase())){
                    logger.debug("回调发送成功");
                    contract = new SignatureContract();
                    contract.setContractCode(info.getContractCode());
                    contract.setSignatureCode(info.getSignatureCode());
                    contract.setUserId(info.getUserId());

                    signatureContractManager.notifySignatureUpdateProcessData(contract, String.valueOf(InterfactType.合同归档.getValue()));

                    info.setStatus(BatchRunStatus.异步通知已完成.getStatus());
                    signatureBatchRunService.updateBatchRunInfo(info);
                    logger.debug("更改数据状态");
                } else {
                    logger.debug("发送回调失败");
                    info.setStatus(BatchRunStatus.异步通知初始化.getStatus());
                    info.setRetryTimes(info.getRetryTimes() - 1);
                    signatureBatchRunService.updateBatchRunInfo(info);
                    logger.debug("减少回调次数");
                }
            } catch (Exception e){
                logger.debug("回调异常");
                logger.warn(e.getMessage());
                e.printStackTrace();
                info.setStatus(BatchRunStatus.异步通知初始化.getStatus());
                info.setRetryTimes(info.getRetryTimes() - 1);
                signatureBatchRunService.updateBatchRunInfo(info);
            }
        }

        Long sp3 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] step2 use times:"+(sp3-sp2)+"--");
        logger.info("--["+tradeNo+"] End callBackTimer , TotalTimes:"+(System.currentTimeMillis()-sp1)+"--");
    }
}